package com.fanxuankai.boot.plumelog.autoconfigure;

import com.fanxuankai.boot.plumelog.interceptor.TraceMethodInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.boot.autoconfigure.condition.ConditionMessage;
import org.springframework.boot.autoconfigure.condition.ConditionOutcome;
import org.springframework.boot.autoconfigure.condition.SpringBootCondition;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ConditionContext;
import org.springframework.context.annotation.Conditional;
import org.springframework.core.env.Environment;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.StringUtils;

/**
 * @author fanxuankai
 */
@Conditional(TraceAutoConfiguration.TraceCondition.class)
public class TraceAutoConfiguration {
    @Bean
    public Advisor plumeLogTraceAdvisor(PlumeLogProperties properties) {
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        advisor.setExpression(properties.getTrace());
        advisor.setAdvice(new TraceMethodInterceptor());
        advisor.getPointcut();
        return advisor;
    }

    protected static class TraceCondition extends SpringBootCondition {
        @Override
        public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
            ConditionMessage.Builder message = ConditionMessage.forCondition("Trace Condition");
            Environment environment = context.getEnvironment();
            String keyValue = environment.getProperty(PlumeLogProperties.TRACE);
            if (StringUtils.hasText(keyValue)) {
                return ConditionOutcome.match(message.foundExactly("provided private or symmetric key"));
            }
            return ConditionOutcome.noMatch(message.didNotFind("provided private or symmetric key").atAll());
        }
    }
}